package com.zh.common.service.impl;

import com.zh.common.dao.RoleDao;
import com.zh.common.dao.RoleMenuDao;
import com.zh.common.dao.UserRoleDao;
import com.zh.common.domain.RoleDO;
import com.zh.common.domain.RoleMenuDO;
import com.zh.common.service.RoleService;
import com.zh.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;





@Service
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleDao roleDao;

	@Autowired
	private RoleMenuDao roleMenuDao;

	@Autowired
	private UserRoleDao userRoleDao;
	
	@Override
	public RoleDO get(String roleId){
		return roleDao.get(roleId);
	}
	
	@Override
	public List<RoleDO> list(Map<String, Object> map){
		return roleDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return roleDao.count(map);
	}
	
	@Override
	@Transactional
	public int save(RoleDO role){
		int count = roleDao.save(role);
		List<String> menuIds = role.getMenuIds();
		String roleId = role.getRoleId();
		List<RoleMenuDO> rms = new ArrayList<>();
		for (String menuId : menuIds) {
			RoleMenuDO rmDo = new RoleMenuDO();
			rmDo.setId(StringUtil.generalKeyword());
			rmDo.setRoleId(roleId);
			rmDo.setMenuId(menuId);
			rms.add(rmDo);
		}
		roleMenuDao.removeByRoleId(roleId);
		if (rms.size() > 0) {
			roleMenuDao.batchSave(rms);
		}
		return count;
	}
	
	@Override
	@Transactional
	public int update(RoleDO role){
		int r = roleDao.update(role);
		List<String> menuIds = role.getMenuIds();
		String roleId = role.getRoleId();
		roleMenuDao.removeByRoleId(roleId);
		List<RoleMenuDO> rms = new ArrayList<>();
		for (String menuId : menuIds) {
			RoleMenuDO rmDo = new RoleMenuDO();
			rmDo.setId(StringUtil.generalKeyword());
			rmDo.setRoleId(roleId);
			rmDo.setMenuId(menuId);
			rms.add(rmDo);
		}
		if (rms.size() > 0) {
			roleMenuDao.batchSave(rms);
		}
		return r;
	}
	
	@Override
	@Transactional
	public int remove(String roleId){
		int count = roleDao.remove(roleId);
		userRoleDao.removeByRoleId(roleId);
		roleMenuDao.removeByRoleId(roleId);
		return count;
	}
	
	@Override
	@Transactional
	public int batchRemove(String[] roleIds){
		int count = roleDao.batchRemove(roleIds);
		userRoleDao.batchRemoveByRoleId(roleIds);
		roleMenuDao.batchRemoveByRoleId(roleIds);
		return count;
	}

	@Override
	public List<RoleDO> getRolesByUserName(String userName, int userType) {
		Map map=new HashMap<>();
		map.put("username",userName);
		map.put("userType",userType);
		return roleDao.getRolesByUserName(map);
	}

}
